function listEvent() {
	jQuery("#search_name").bind('keypress', function(e) {
		var curKey = e.which;
		if(curKey == 13) {
			gets();
			return false;
		}
	});
}

function getByUrl(data){
    $.post("../../search",{
        url:"http://dpadmin.grid.sina.com.cn",
        name:data
    } ,lists);

    $.post("../../search",{
        url:"http://dpadmint.grid.sina.com.cn",
        name:data
    } ,lists);
}

function gets() {
	var sn = $("#search_name").val();
	var url = $("#url").val();
	$("#list").empty();
	$.blockUI({
		message: "<img src='../../img/loading.gif'/>",
		css: { 
	        padding:        0, 
	        margin:         0, 
	        width:          '50', 
	        top:            '40%', 
	        left:           '50%', 
	        textAlign:      'center', 
	        color:          '#000', 
	        border:         '3px solid #aaa', 
	        backgroundColor:'#fff', 
	        cursor:         'wait' 
	    }
	}); 
	$.post("../../search",{
		url:url,
		name:sn
	} ,lists);
}

function build(){
	$(".but1").click( function() {
		var contact  = $(this).parent().children("input[name='contact']").val();
		var desp  = $(this).parent().children("input[name='desp']").val();
		var id  = $(this).parent().children("input[name='id']").val();
		$.post("../../modify",{
			id:id,
			contact:contact,
			desp:desp
		});
		alert('修改成功');
	});
}

function lists(data) {
	if(!data || data.length ==0 ) return false;
	jQuery("#list").empty();
	var html = '';
//	html += '<tr class="info"><td>产品线</td><td>端口</td><td>IDC</td><td>IP</td><td>角色</td><td>内存(G)</td><td>磁盘(G)</td><td>利用率(%)</td></tr>';//<td>统计</td><td>联系人</td>
	for(var k in data) {
		var row = data[k];
		html += '<h2><a href="' + row.cacti_url +'" target="_black">' + k + '<img src="../../img/line2.png" width="30" height="30"></a></h2>';
		html += '<div class="alert alert-success"><div class="row-fluid"><div class="span6"><form action="modify" method="post" name="mod"><input type="hidden" class=".sel" name="id" value="'+row.cpunit_id+'"/>';
		html += '<h3>基础信息</h3>';
		html += get_contact(row.contact);
		html += '</form></div>';
		html += '<div class="span6"><h3>每日数据汇总</h3>' + get_stat(row.stat);
		html += '<h3>资源列表</h3>'+row.port.join(',') + '(端口数:'+ row.port.length +')</div></div>';
		html += '<div class="row-fluid"><div id="'+row.cpunit_id+'a" style="margin: 0 auto"></div></div>';
		html += '<div class="row-fluid"><div id="'+row.cpunit_id+'b" style="margin: 0 auto"></div></div>';
		html += '<div class="row-fluid"><div id="'+row.cpunit_id+'c" style="margin: 0 auto"></div></div>';
		html += '<div class="row-fluid"><div id="'+row.cpunit_id+'d" style="margin: 0 auto"></div></div></div></div>';
		html += '<table class="table table-bordered table-striped" width="100%">';
		html += '<tr class="info"><td>IDC</td><td>IP</td><td>角色</td><td>内存(G)</td><td>磁盘(G)</td><td>利用率(%)</td></tr>';
//		html += '<tr name="redis_info_item" class=" vertical-align:middle"> <td class="cpunit">' + '<a href="' + row.cacti_url +'" target="_black">' + k + '</a><br/>'+get_contact(row.contact)+'<br/>' + get_stat(row.stat) + '</td>';
//		if(row.port instanceof Array) {
//		html += '<td class="port">' + row.port.join(' , ').replace(/^\s+/g,"").replace(/\s+$/g,"") + '<p>(端口数:'+ row.port.length +')</p> </td>';
//		html += '<td class="port">' + '<p class="wrap">' + row.port.join('<br/>') + '</p><p>(端口数:'+ row.port.length +')</p> </td>';
		html += get_idc(row.idc);
//		html += '<td> ' + get_stat(row.stat) + '</td>';
//		html += '<td> ' + get_contact(row.contact) + '</td>';
		html += '</table>';
		$.post("../../chart",{
			cname:	k,
			cpid:row.cpunit_id
		},paint);
	}
	jQuery("#list").append(html);
	build();
	$("#myTable").hide();
	$.unblockUI(); 
}

function get_idc(data) {
	if(!data) return '';
	if (! data instanceof Array) { 
		console.log('data not array');
		return '';
	}
	var html = '';//idc array
	for(var k in data) {
		var row = data[k]; //idc row
		var ip_num = Object.keys(row).length;
		if(ip_num) {
			
			var i = 0;
			for( var ip in row) {
				var ip_info = row[ip];
				if(i==0){
					html += '<tr><td class="idc" style="vertical-align:middle" rowspan="'+ip_num+'">' + k + '<p>(' + ip_num + '台)</p> </td>';
				}else{
					html += '<tr>';
				}
				i++;
//				html += '<tr name="tr_' + ip_info['ip'] + '" >';  
				html += '<td class="ip">' +'<a href="'+ ip_info['ganglia_url'] +'" target="_black">' + ip_info['ip'] +  '<img src="../../img/line2.png" width="20" height="20"></a></td>';
				if(ip_info['role']) {
					html += '<td class="role">' + ip_info['role'] +  '</td>'} else {
					html += '<td class="role">' +   '--'  +  '</td>'
				} 
				if(ip_info['mem_total']) {
					html += '<td class="mem">' + Math.round(ip_info['mem_used']*10)/10 + '/' + Math.round(ip_info['mem_total']*10)/10 +  '</td>'}
				else {
					html += '<td class="mem">' +   '--'  +  '</td>'
				} 
				if(ip_info['disk_total']) {
					html += '<td class="disk">' + Math.round(ip_info['disk_used']*10)/10 + '/' + Math.round(ip_info['disk_total']*10)/10 +  '</td>'	}
				else {
					html += '<td class="disk">' +   '--'  +  '</td>'
				}
				if(ip_info['util']) {
					util = ip_info['util']['full_uti'] 
					if(util >= 80) {
						html += '<td class="util" style="color:red">' + util + '</td>'
					} else if ( util >= 50 ) {
						html += '<td class="util" style="color:#D9B300">' + util + '</td>'
					} else if ( util >= 20 ) {
						html += '<td class="util" style="color:#00BB00">' + util + '</td>'
					} else {
						html += '<td class="util" style="color:blue">' + util + '</td>'
					}  
				}
				 else {
					html += '<td class="util">' +   '--'  +  '</td>'
				}
				//html += '<td class="net">' + ip_info['net'] +  '</td>'	
				html += '</tr>';
			}
		}
//		html += '</td>'; //ip table
//		html += '</tr>';
	}
//	html += '</table>';
	return html;
}

function get_stat(data) {
	if (! data instanceof Array) {
		console.log('get_stat param not array');
		return '';
	}
	//取小数点3位
	var total_command = data.total_command == undefined ? '--' : Math.round(data.total_command*1000)/1000;
	var used_memory = data.used_memory == undefined ? '--' : Math.round(data.used_memory*1000)/1000;
	var total_read = data.total_read == undefined ? '--' : Math.round(data.total_read*1000)/1000;
	var total_write = data.total_write == undefined ? '--' : Math.round(data.total_write*1000)/1000;

//	var html = '<table class="t_stat">';
//	html += '<tr> <td width="50%"> Cmd:' + total_command + '(亿)</td> <td> Read:' + total_read + ' (亿)</td></tr>';
//	html += '<tr> <td> Mem:' + used_memory + '(GB)</td> <td> Write:' + total_write + ' (亿)</td></tr>';
//	html += '</table>';	
	
	var html ='';
	html +=  '命令总数:' + total_command + '(亿)<br/>';
	html += '内存使用:' + used_memory + '(GB)<br/>';
	html += '写次数:' + total_write + ' (亿)<br/>';
	html += '读次数:' + total_read + ' (亿)';
	return html;
}

function get_contact(data) {
//	if(!data) return '';
	if (! data instanceof Array) {
		console.log('get_contact param not array');
		return '';
	}
	var contact =  data.contact == undefined ? '' : data.contact ;
	var dba_group = data.dbname == undefined ? '' : data.dbname;
	var desp = data.desp == undefined ? '':data.desp;
//	var html = '<table class="">';
	var html ='';
//	html += '<tr> <td>业务负责人:' + contact + '</td> </tr>';
//	html += '<tr> <td>&nbsp;&nbsp;运维组:' + dba_group + '</td> </tr>';
	html += '业务负责人:<input name="contact" class=".sel" type="text" value="' + contact+'"/>&nbsp;&nbsp;<br/>';
	html += '业务描述:<input name="desp" class=".sel" type="text" value="' + desp + '"/><br/><input type="button" name="modify" class="but1" value="确认修改"/><br/>';
	html += '运维组:' + dba_group;
//	html += '</table>';	
	return html;
}
// sleep ms
function sleep(numberMillis) {
	var now = new Date();
	var endTime = now.getTime() + numberMillis;
	while(true) {
		now = new Date();
		console.log(now.getTime() + " --> " + endTime);
		if(now.getTime() > endTime ) {
			return false;
		}
	} 
}
    
function paint(arr){
	var cn = arr.cpid;
	$('#'+cn+'a').highcharts({
        chart: {
        	type: 'spline',
            height: 250,
            zoomType: 'x',
            plotBorderWidth: 1,
        },
        colors:['#058DC7'] 
        ,
        legend:{
        	enabled:false
        }
        ,
        plotOptions: {
            spline: {
                lineWidth: 1.8,
                fillOpacity: 0.1,
                marker: {
                    enable: false,
                    radius: 0
                }}
        },
        title: {
            text: '90天command总数据量统计',
        },
        xAxis: {
            categories: arr.categories,
            tickInterval:5
        },
        yAxis: {
            title: {
                text: '单位：亿条'
            }
        },
        series: [{
            name: 'command count',
            data: arr.command
        }]
    });
	
	$('#'+cn+'b').highcharts({
        chart: {
        	type: 'spline',
            height: 250,
            zoomType: 'x',
            plotBorderWidth: 1,
        },
        colors:['#24CBE5'] 
        ,
        plotOptions: {
            spline: {
                lineWidth: 1.8,
                fillOpacity: 0.1,
                marker: {
                    enable: false,
                    radius: 0
                }}
        },
        legend:{
        	enabled:false
        }
        ,
        title: {
            text: '90天read总数量统计',
        },
        xAxis: {
            categories: arr.categories,
            tickInterval:5
        },
        yAxis: {
            title: {
                text: '单位：亿条'
            }
        },
        series: [{
            name: 'read count',
            data: arr.read
        }]
    });
	
	$('#'+cn+'c').highcharts({
        chart: {
        	type: 'spline',
            height: 250,
            zoomType: 'x',
            plotBorderWidth: 1,
        },
        colors:['#6AF9C4'] 
        ,
        legend:{
        	enabled:false
        }
        ,
        plotOptions: {
            spline: {
                lineWidth: 1.8,
                fillOpacity: 0.1,
                marker: {
                    enable: false,
                    radius: 0
                }}
        },
        title: {
            text: '90天write总数量统计',
        },
        xAxis: {
            categories: arr.categories,
            tickInterval:10
        },
        yAxis: {
            title: {
                text: '单位：亿条'
            }
        },
        series: [{
            name: 'write count',
            data: arr.write
        }]
    });
	
	$('#'+cn+'d').highcharts({
        chart: {
        	type: 'spline',
            height: 250,
            zoomType: 'x',
            plotBorderWidth: 1,
        },
        colors:['#FF9655']
        ,
        legend:{
        	enabled:false
        }
        ,
        plotOptions: {
            spline: {
                lineWidth: 1.8,
                fillOpacity: 0.1,
                marker: {
                    enable: false,
                    radius: 0
                }}
        },
        title: {
            text: '90天memory使用量统计',
        },
        xAxis: {
        	categories: arr.categories,
        	tickInterval:5
        },
        yAxis: {
            title: {
                text: '单位：GB'
            }
        },
        series: [{
            name: 'memory count',
            data: arr.memory
        }]
    });
}